package JdbcTest.Jdbc;

import com.mysql.cj.jdbc.Driver;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.*;
import java.util.Properties;

/*
模拟转帐，来演示事务机制
    con.setAutoCommit(false) 关闭事务自动提交机制
    con.commit 提交事务
    con.rollback 回滚事务
 */
public class JdbcTest4 {
    public static void main(String[] args) {
        Connection con = null;
        PreparedStatement pst = null;
        FileInputStream fis = null;
        Properties properties = new Properties();
        try {
            fis = new FileInputStream("src/JdbcTest/Jdbc/DatabaseFile.properties");
            properties.load(fis);
            Class.forName(properties.getProperty("Driver"));
            con = DriverManager.getConnection(properties.getProperty("url"),properties.getProperty("username"),properties.getProperty("password"));
            //关闭事务自动提交机制
            con.setAutoCommit(false);
            String sql = "update t_account set balance = balance + ? where id = ?";
            pst = con.prepareStatement(sql);
            pst.setDouble(1,1000.0);
            pst.setInt(2,1);
            int count = pst.executeUpdate();
            //模拟转账中出现异常
            //String s = null;
            //s.toString();
            String sql1 = "update t_account set balance = balance - ? where id = ?";
            pst = con.prepareStatement(sql1);
            pst.setDouble(1,1000);
            pst.setInt(2,2);
            count += pst.executeUpdate();
            con.commit();
            System.out.println(count == 2 ? "修改成功":"修改失败");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally {
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (pst != null) {
                try {
                    pst.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (con != null) {
                try {
                    con.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
